<template>
  <div class="app-container">
    <CommonContainer title="基础信息">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="top">
        <el-row :gutter="30">
          <el-col :span="8">
            <el-form-item label="规则名称:" prop="ruleName">
              <el-input v-model="form.ruleName" clearable placeholder="请输入规则名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品方案" prop="planIds">
              <el-select v-model="form.planIds" multiple placeholder="请选择产品方案" style="width: 100%" @change="changePlan">
                <el-option v-for="(item,index) in planList" :key="item.id" :label="item.schemeName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="客户类型:" prop="customerType">
              <el-select v-model="form.customerType" clearable style="width: 100%">
                <template v-for="dict in dict.type.customer_type">
                  <el-option :label="dict.label" :value="parseInt(dict.value)" :key="dict.value"></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="是否需CRC审批:" prop="needCrc">
              <el-radio-group v-model="form.needCrc">
                <el-radio :label="1">需要</el-radio>
                <el-radio :label="2">不需要</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="租赁用途:" prop="leasePurpose">
              <e-switch v-model="form.leasePurpose"></e-switch>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="客户标签:" prop="customerSource">
              <e-switch v-model="form.customerSource"></e-switch>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="客户属性:" prop="clientProperty">
              <e-switch v-model="form.clientProperty"></e-switch>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="客户等级:" prop="customerGrade">
              <e-switch v-model="form.customerGrade"></e-switch>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="租期:" prop="leaseTerm">
              <e-switch v-model="form.leaseTerm"></e-switch>
            </el-form-item>
          </el-col>

          <el-col :span="8">

            <div class="flex-row-center">
              <el-form-item label="台数:" prop="unitsStatus" style="width: 70px">
                <e-switch v-model="form.unitsStatus"></e-switch>
              </el-form-item>
              <template v-if="form.unitsStatus==1">
                <el-form-item prop="unitsType" style="width: 50%;position: relative;top: 18px">
                  <el-select v-model="form.unitsType" clearable style="width: 100%">
                    <template v-for="dict in dict.type.credit_review_units">
                      <el-option :label="dict.label" :value="parseInt(dict.value)" :key="dict.value"></el-option>
                    </template>
                  </el-select>
                </el-form-item>

                <template v-if="form.unitsType > 2">
                  <el-form-item prop="unitsDays" style="width: 130px;position: relative;top: 18px;left: 5px">
                    <el-input v-model="form.unitsDays" clearable>
                      <template slot="append">天内</template>
                    </el-input>
                  </el-form-item>
                </template>
              </template>
            </div>


          </el-col>

          <el-col :span="8">
            <div class="flex-row-center" style="position: relative">
              <el-form-item label="新车采购总额/旧车当前估值总额:" prop="amountStatus">
                <e-switch v-model="form.amountStatus"></e-switch>
              </el-form-item>
              <template v-if="form.amountStatus==1">
                <div class="flex-row-center" style="position: absolute;top: 34px;left: 70px">
                  <el-form-item prop="amountType" style="width: 100%;">
                    <el-select v-model="form.amountType" clearable style="width: 100%">
                      <template v-for="dict in dict.type.credit_review_amount">
                        <el-option :label="dict.label" :value="parseInt(dict.value)" :key="dict.value"></el-option>
                      </template>
                    </el-select>
                  </el-form-item>

                  <template v-if="form.amountType > 2">
                    <el-form-item prop="amountDays" style="width: 200px;position: relative;left: 10px">
                      <el-input v-model="form.amountDays" clearable>
                        <template slot="append">天内</template>
                      </el-input>
                    </el-form-item>
                  </template>
                </div>
              </template>
            </div>
          </el-col>

        </el-row>
      </el-form>
    </CommonContainer>
    <CommonContainer title="规则配置" v-show="switchOneOpen">
      <div class="card-wrap paddingAll20">
        <div class="table-title-wrap justify-start">
          <el-button type="primary" size="mini" @click="configAddRules">新增规则
          </el-button>
        </div>

        <el-table
            :data="form.crRuleItems"
            :header-cell-style="{ background: '#FAFAFA', color: '#000000' }" border :key="isUpdate">
          <template slot="empty">
            <el-empty :image-size="50" description="暂无规则配置信息"></el-empty>
          </template>
          <el-table-column
              v-if="form.leasePurpose==1"
              key="leasePurpose"
              align="center"
              prop="leasePurpose"
              label="租赁用途"
              min-width="120">
            <template v-slot="{row}">
              <dict-tag :options="dict.type.rental_purpose" :value="row.leasePurpose"/>
            </template>
          </el-table-column>
          <el-table-column
              v-if="form.customerSource==1"
              key="customerSource"
              align="center"
              prop="customerSource"
              label="客户标签"
              min-width="120">
            <template v-slot="{row}">
              <dict-tag :options="dict.type.customer_label" :value="row.customerSource"/>
            </template>
          </el-table-column>
          <el-table-column
              v-if="form.clientProperty==1"
              key="clientProperty"
              align="center"
              prop="clientProperty"
              label="客户属性"
              min-width="120">
            <template v-slot="{row}">
              <dict-tag :options="dict.type.customer_property" :value="row.clientProperty"/>
            </template>
          </el-table-column>
          <el-table-column
              v-if="form.customerGrade==1"
              key="customerGrade"
              align="center"
              prop="customerGrade"
              label="客户等级"
              min-width="120">
            <template v-slot="{row}">
              <dict-tag :options="dict.type.customer_level" :value="row.customerGrade"/>
            </template>
          </el-table-column>

          <el-table-column
              v-if="form.leaseTerm==1"
              key="leaseTerm"
              align="center"
              prop="minLeaseTerm"
              label="租期(月)"
              min-width="120">
            <template v-slot="{row}">
              {{ `(${row.minLeaseTerm>0? row.minLeaseTerm:0},${(row.maxLeaseTerm&&row.maxLeaseTerm!=0)?row.maxLeaseTerm:'3600'}]` }}
            </template>
          </el-table-column>
          <el-table-column
              v-if="form.unitsStatus==1 && form.unitsType"
              key="unitsType"
              align="center"
              prop="unitsType"
              label="30天内累计申请台数(台)"
              min-width="220">
            <template slot="header" slot-scope="scope">
              <div class="inline-flex">
                <span v-if="form.unitsType>2">{{ form.unitsDays }}天内</span>
                <dict-tag :options="dict.type.credit_review_units" :value="parseInt(form.unitsType)"/>
              </div>
            </template>
            <template v-slot="{row}">
              {{ `(${row.minUnits>0? row.minUnits:0},${(row.maxUnits&&row.maxUnits!=0)?row.maxUnits:'∞'}]` }}
            </template>
          </el-table-column>
          <el-table-column
              v-if="form.amountStatus==1 &&  form.amountType"
              key="amountType"
              align="center"
              prop="updateTime"
              label="30天内累计申请金额(元)"
              min-width="220">
            <template slot="header" slot-scope="scope">
              <div class="inline-flex">
                <span v-if="form.amountType>2">{{ form.amountDays }}天内</span>
                <dict-tag :options="dict.type.credit_review_amount" :value="parseInt(form.amountType)"/>
              </div>
            </template>
            <template v-slot="{row}">
              {{ `(${row.minAmount>0? row.minAmount:0},${(row.maxAmount&&row.maxAmount!=0)?row.maxAmount:'∞'}]` }}
            </template>
          </el-table-column>


          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200" fixed="left">
            <template slot-scope="scope">
              <el-button size="small" type="text"
                         @click="rulesConfigOperation(1,scope.$index, scope.row)">编辑
              </el-button>
              <el-button size="small" type="text"
                         @click="rulesConfigOperation(2, scope.$index,scope.row)">作废
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </CommonContainer>

    <div class="card-wrap flex justify-end card-padding">
      <el-button @click="cancel">取消</el-button>
      <el-button :loading="buttonLoading" type="primary" @click="submitForm">保存</el-button>
    </div>
    <config-add-rules ref="configAddRules" :rental-purpose="dict.type.rental_purpose" :customer-source="dict.type.customer_label" :customer-level="dict.type.customer_level"
                      :customer-property="dict.type.customer_property" :parentForm="form" :credit-review-units="dict.type.credit_review_units"
                      :credit-review-amount="dict.type.credit_review_amount"
                      @success="configAddRulesSuccess"></config-add-rules>


  </div>
</template>

<script>

import ConfigAddRules from './components/addRules.vue'
import * as approveRulesApi from "@/api/letterReview/suggestionApproveRules";
import {planList} from "@/api/contractTemplate/contractTemplate";

export default {
  name:'SuggestionRulesAdd',
  components: {ConfigAddRules},
  dicts: ['business_type', 'customer_type', 'credit_review_units', 'credit_review_amount', 'rental_purpose', 'customer_label', 'customer_level', 'customer_property'],
  data() {
    return {
      buttonLoading: false,
      isUpdate: Math.random(),
      form: {
        id: null,
        businessType: this.$route.query.businessType,
        ruleName: null,
        planId: null,
        planIds: null,
        planName: null,
        customerType: null,
        needCrc: 1,
        leasePurpose: 1,
        customerSource: 1,
        clientProperty: 1,
        customerGrade: 1,
        leaseTerm: 1,
        unitsStatus: 2,
        unitsType: null,
        unitsDays: 30,
        amountStatus: 2,
        amountType: null,
        amountDays: 30,
        crRuleItems: [],
      },
      rules: {
        ruleName: [
          {required: true, message: '请输入规则名称', trigger: 'change'},
        ],
        planIds: [
          {required: true, message: '请选择产品方案', trigger: ['blur']},
        ],
        customerType: [
          {required: true, message: '请选择客户类型', trigger: 'change'},
        ],
        unitsType: [
          {required: true, message: '请选择台数', trigger: 'change'},
        ],
        unitsDays: [
          {required: true, message: '请输入累计台数统计天数', trigger: 'change'},
        ],
        amountType: [
          {required: true, message: '请选择新车采购总额/旧车当前估值总额', trigger: 'change'},
        ],
        amountDays: [
          {required: true, message: '请输入累计申请金额统计天数', trigger: 'change'}
        ]
      },
      selectedFilesList: [],
      planList: []

    };
  },


  watch: {
    selectedFilesList(val) {
      if (val.length > 0) {
        let basicDataIds = []
        let basicDataNames = []
        let chooseOneDataIds = []
        let chooseOneDataNames = []
        let selectiveDataIds = []
        let selectiveDataNames = []
        val.map((item) => {
          if (item.type == 1) {
            basicDataIds.push(item.id)
            basicDataNames.push(item.dataName)
          } else if (item.type == 2) {
            chooseOneDataIds.push(item.id)
            chooseOneDataNames.push(item.dataName)
          } else if (item.type == 3) {
            selectiveDataIds.push(item.id)
            selectiveDataNames.push(item.dataName)
          }
        })
        this.filesConfigs[0].ids = basicDataIds;
        this.filesConfigs[0].infos = basicDataNames.join(',')
        this.form.basicData = basicDataIds.join(',')

        this.filesConfigs[1].ids = chooseOneDataIds;
        this.filesConfigs[1].infos = chooseOneDataNames.join(',')
        this.form.chooseOneData = chooseOneDataIds.join(',')

        this.filesConfigs[2].ids = selectiveDataIds;
        this.filesConfigs[2].infos = selectiveDataNames.join(',')
        this.form.selectiveData = selectiveDataIds.join(',')

      }
    }
  },
  computed: {
    switchOneOpen() {
      let open = false;
      if (this.form.leasePurpose == 1 || this.form.customerSource == 1 || this.form.clientProperty == 1 || this.form.customerGrade == 1 || this.form.leaseTerm == 1 || this.form.unitsStatus == 1 || this.form.amountStatus == 1) {
        open = true
      }
      return open
    }
  },
  mounted() {
    this.form.id = this.$route.query.id;
    if (this.form.id) {
      this.getDetail()
    }
    this.getPlanList()
  },
  methods: {

    //编辑回显
    getDetail() {
      approveRulesApi.suggestionRuleDetail(this.form.id).then(res => {
        this.form = res.data;
        if (this.form.planId) {
          this.$set(this.form, 'planIds', this.form.planId.split(','))
        }
      })
    },
    //获取产品方案
    getPlanList() {
      planList({
        businessSource: this.$route.query.businessType,
        shelveStatus : 1
      }).then(res => {
        this.planList = res.data;
      })
    },
    // 选择产品方案
    changePlan(val) {
      console.log('plans', val)
      let planNames = []
      this.planList.forEach(item => {
        if (val && val.length > 0) {
          val.forEach(id => {
            if (item.id == id) {
              planNames.push(item.schemeName)
            }
          })
        }
      })
      this.form.planName = planNames.join(',');
    },
    rulesConfigOperation(type, index, row) {
      switch (type) {
        case 1://编辑
          this.$refs.configAddRules.show(2, index, row)
          break
        case 2://删除
          this.$confirm('确认删除该规则吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then((cof) => {
            this.form.crRuleItems.splice(index, 1)
          })
          break
      }
    },

    configAddRules() {

      // 新增规则->台数必填校验
      if (this.form.unitsStatus == 1) {
        if (!this.form.unitsType) {
          this.$message.error('请选择台数')
          return
        } else if (this.form.unitsType > 2 && (this.form.unitsDays == '' || this.form.unitsDays == null)) {
          this.$message.error('请选择输入统计天数')
          return
        }
      }

      // 新增规则->金额必填校验
      if (this.form.amountStatus == 1) {
        if (!this.form.amountType) {
          this.$message.error('请选择新车采购总额/旧车当前估值总额')
          return
        } else if (this.form.amountType > 2 && (this.form.amountDays == '' || this.form.amountDays == null)) {
          this.$message.error('请选择输入统计天数')
          return
        }
      }
      this.$refs.configAddRules.show(1)
    },

    configAddRulesSuccess(val) {
      if (val.type == 2) {
        this.form.crRuleItems[val.editIndex] = val.rulesItem
        this.isUpdate = !this.isUpdate;
      } else {
        this.form.crRuleItems.push(val.rulesItem)
      }

      console.log('规则配置列表---', this.form.crRuleItems)
    },

    // 资料配置
    filesConfig(row) {
      if (this.form.customerType) {
        this.$refs.filesConfig.show(row, this.selectedFilesList)
      } else {
        this.$message.error('请选择客户类型')
      }
    },
    filesConfigSuccess(selectedFiles) {
      this.selectedFilesList = [...this.selectedFilesList, ...selectedFiles]
    },
    cancel() {
      this.$router.back()
      this.$store.dispatch('tagsView/delView', this.$route)
    },
    submitForm() {
      if (this.switchOneOpen && (this.form.crRuleItems.length == 0 || this.form.crRuleItems == null)) {
        this.$message.error('请至少配置一条规则')
        return
      }
      this.form.planId = this.form.planIds.join(',')
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.buttonLoading = true
          if (this.form.id) {
            approveRulesApi.suggestionRuleUpdate(this.form).then(res => {
              this.$message.success('编辑成功')
              this.cancel()
            }).finally(() => {
              this.buttonLoading = false
            })
          } else {
            approveRulesApi.suggestionRuleAdd(this.form).then(res => {
              this.$message.success('新增成功')
              this.cancel()
            }).finally(() => {
              this.buttonLoading = false
            })
          }
        }
      })

    },
  }
};
</script>


<style lang="scss" scoped>
::v-deep .el-form--label-top .el-form-item__label {
  padding: 0;
}

.el-form-item {
  margin-bottom: 15px;
  width: 70%;
}



</style>
